package com.jinghua.treatment.wechat.biz;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jinghua.treatment.entity.DPRelationship;
import com.jinghua.treatment.entity.SysDoctor;
import com.jinghua.treatment.entity.SysPatient;
import com.jinghua.treatment.entity.SysWechatAccount;
import com.jinghua.treatment.mapper.DPRelationshipMapper;
import com.jinghua.treatment.mapper.SysDoctorMapper;
import com.jinghua.treatment.mapper.SysWechatAccountMapper;
import com.jinghua.treatment.service.SysPatientService;
import com.jinghua.treatment.tools.IDGenerator;
import com.jinghua.treatment.tools.PropertyUtil;
import com.jinghua.treatment.wechat.entity.EventXML;
import com.jinghua.treatment.wechat.entity.JSONNewsEntity;
import com.jinghua.treatment.wechat.entity.TextXML;
import com.jinghua.treatment.wechat.util.HttpUtil;
import com.jinghua.treatment.wechat.util.WechatUtil;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.Element;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

@Component
public class WechatBiz {


    @Resource
    private SysDoctorMapper sysDoctorMapper;

    @Resource
    private SysWechatAccountMapper sysWechatAccountMapper;

    @Resource
    private SysPatientService sysPatientService;

    @Resource
    private  DPRelationshipMapper dpRelationshipMapper;


    Logger log = LogManager.getLogger(WechatBiz.class);
    String server = PropertyUtil.getConfig("app.server");

    @Transactional
    public void doBussiness(Document document, HttpServletRequest request, HttpServletResponse response) throws IOException {
        Element root = document.getRootElement();
        String msgType = root.selectSingleNode("MsgType").getText();
        if ("text".equals(msgType)) {
            TextXML textXML = parseTextObject(root);
            if ("ys".equals(textXML.getContent())) {
                String doctorWechatId = textXML.getFromUserName();
                SysWechatAccount example = new SysWechatAccount();
                example.setOpenid(doctorWechatId);
                List<SysWechatAccount> wechatAccounts = sysWechatAccountMapper.selectByExample(example);
                SysWechatAccount   wechatAccount  =  fetchWechatInfo(doctorWechatId);
                if (wechatAccounts != null && wechatAccounts.size() > 0) {//已经绑定微信
                    SysWechatAccount sysWechatAccount = wechatAccounts.get(0);
                    //查看是否认证,先查看有没有此医生
                    SysDoctor docExample = new SysDoctor();
                    docExample.setWechat(doctorWechatId);
                    List<SysDoctor> sysDoctors = sysDoctorMapper.selectByExample(docExample);
                    if (sysDoctors != null && sysDoctors.size() > 0) {//有，再查看有没有认证
                        SysDoctor sysDoctor = sysDoctors.get(0);
                        String xml = buildTWXML(doctorWechatId, sysDoctor.getDoctorname() + ",欢迎回来，点击进入我的工作室",
                                server+"/mod-page/images/wechat/doc-studio.jpg",
                                server+"/mod-page/doctor_home.html?doctorId=" + sysDoctor.getDoctorId(),
                                "前往我的工作室-->");
                        response.getWriter().write(xml);
                    } else {//没有注册，引导到医生注册页面
                        String xml = buildTWXML(doctorWechatId, wechatAccount.getNickname() + ",欢迎您，您还未注册为医师，请先注册",
                                server+"/mod-page/images/wechat/doc-reg-guider.jpg",
                                server+"/mod-page/studio/doctor_regist.html?wid="+doctorWechatId+"&wechatName="+java.net.URLEncoder.encode(sysWechatAccount.getNickname(),"UTF-8")+"&_="+new Date().getTime(),
                                "前往注册医师-->");
                        response.getWriter().write(xml);
                    }
                } else {//未绑定微信,先去注册
                    String xml = buildTWXML(doctorWechatId, wechatAccount.getNickname()+",您还未注册为医师，请先注册",
                            server+"/mod-page/images/wechat/doc-reg-guider.jpg",
                            server+"/mod-page/studio/doctor_regist.html?wid="+doctorWechatId+"&wechatName="+java.net.URLEncoder.encode(wechatAccount.getNickname(),"UTF-8"),
                            "前往注册医师-->");
                    response.getWriter().write(xml);

                }
            }else if("hz".equals(textXML.getContent())){//患者
                String patientWechatId = textXML.getFromUserName();
                SysWechatAccount example = new SysWechatAccount();
                example.setOpenid(patientWechatId);
                List<SysWechatAccount> wechatAccounts = sysWechatAccountMapper.selectByExample(example);
                SysWechatAccount   wechatAccount  =  fetchWechatInfo(patientWechatId);

                if (wechatAccounts != null && wechatAccounts.size() > 0) {//已经绑定微信
                    SysWechatAccount sysWechatAccount = wechatAccounts.get(0);
                    //如果已经绑定微信，检查有没有注册用户
                    SysPatient sysPatient = sysPatientService.selectByWechat(patientWechatId);
                    if (sysPatient!=null) {//有，跳往患者主页
                        String xml = buildTWXML(patientWechatId, sysPatient.getPatientname() + ",欢迎回来，点击进入我的主页",
                                server+"/mod-page/images/wechat/patient_bg.jpg",
                                server+"/mod-page/patient_home.html?patientId=" + sysPatient.getPatientId(),
                                "前往我的主页-->");
                        response.getWriter().write(xml);
                    } else {//没有注册，引导到患者注册页面
                        String xml = buildTWXML(patientWechatId, wechatAccount.getNickname() + ",欢迎您，您还未注册，请先注册",
                                server+"/mod-page/images/wechat/patient_reg.jpg",
                                server+"/mod-page/patient/patient_regist.html?wid="+wechatAccount.getOpenid()+"&wechatName="+java.net.URLEncoder.encode(wechatAccount.getNickname(),"UTF-8")+"&_="+new Date().getTime(),
                                "前往注册-->");
                        response.getWriter().write(xml);
                    }
                } else {//未绑定微信,先去注册
                    //没有注册，引导到患者注册页面
                    String xml = buildTWXML(patientWechatId, wechatAccount.getNickname() + ",欢迎您，您还未注册，请先注册",
                            server+"/mod-page/images/wechat/patient_reg.jpg",
                            server+"/mod-page/patient/patient_regist.html?wid="+wechatAccount.getOpenid()+"&wechatName="+java.net.URLEncoder.encode(wechatAccount.getNickname(),"UTF-8")+"&_="+new Date().getTime(),
                            "前往注册-->");
                    response.getWriter().write(xml);
                }
            }
        }else if("event".equals(msgType)){//微信推送的事件，如用户关注等
            EventXML eventXML = parseEventObject(root);
            //获取Event 字段
            String eventType = root.selectSingleNode("Event").getText();//这里event 有7中，目前只处理扫描了医生扫描了二维码后的场景
            //System.out.println("xml:" + root.asXML());
            String eventKey =eventXML.getEventKey();

            if("SCAN".equals(eventType)){//用户之前没有关注过公众号的 推送欢迎信息，已关注，则发送医生信息
                String doctorWechat = eventKey.replace("qrscene_","");
                char bizType = doctorWechat.charAt(0);
                //查询医生的信息
                SysDoctor docExample = new SysDoctor();
                docExample.setWechat(doctorWechat.substring(1));
                List<SysDoctor> sysDoctors = sysDoctorMapper.selectByExample(docExample);
                SysDoctor sysDoctor = null;
                if(sysDoctors!=null&&sysDoctors.size()>0){
                     sysDoctor  = sysDoctors.get(0);
                }
                if('#'==bizType){//# 患者扫描，添加患者
                        //判断是不是自己关注自己
                        if(sysDoctor.getWechat().equals(eventXML.getFromUserName())){
                            String xml  =buildWBXML(eventXML.getFromUserName(),"自己不能关注自己");
                            response.getWriter().write(xml);
                            return ;
                        }
                        SysPatient  sysPatient = sysPatientService.selectByWechat(eventXML.getFromUserName());
                        SysWechatAccount wechatAccount = fetchWechatInfo(eventXML.getFromUserName());
                        if(sysPatient==null) {//库中没有记录，插入
                            sysPatient = new SysPatient();
                            sysPatient.setPatientname(wechatAccount.getNickname());
                            sysPatient.setWechat(eventXML.getFromUserName());
                            sysPatient.setSex("0".equals(wechatAccount.getSex()) ? "男" : "女");
                            sysPatient.setPatientCreatedate(new Date());
                            sysPatient.setPatientPicPath(wechatAccount.getHeadimgurl());
                            sysPatientService.insert(sysPatient);
                        }
                        //查关系表是不是已经有关注
                        DPRelationship example = new DPRelationship();
                        example.setPatientId(sysPatient.getPatientId());
                        example.setDoctorId(sysDoctor.getDoctorId());
                        List  dprList = dpRelationshipMapper.selectByExample(example);
                        if(dprList==null||dprList.size()==0){
                            DPRelationship dpRelationship  = new DPRelationship();
                            dpRelationship.setDoctorId(sysDoctor.getDoctorId());
                            dpRelationship.setDpCreatetiondate(new Date());
                            dpRelationship.setPatientId(sysPatient.getPatientId());
                            dpRelationshipMapper.insert(dpRelationship);
                        }

                        //如果没有绑定微信，加一条数据
                        SysWechatAccount wechatExample = new SysWechatAccount();
                        wechatExample.setOpenid(wechatAccount.getOpenid());
                        List<SysWechatAccount> accounts = sysWechatAccountMapper.selectByExample(wechatExample);
                        if(accounts==null||accounts.size()<=0){
                            wechatAccount.setUuid(IDGenerator.uuid());
                            sysWechatAccountMapper.insert(wechatAccount);
                        }
                        String xml  =buildWBXML(eventXML.getFromUserName(),"您已成功关注"+sysDoctor.getDoctorname()+"医生，请尽快&lt;a href=&quot;"+server+"/mod-page/patient/patient_info_detail_extract.html?patientId="+sysPatient.getPatientId()+"&quot;&gt;完善您的个人信息&lt;/a&gt;，以方便医生诊断");
                        response.getWriter().write(xml);
                }else if('@'==bizType){//@ 问诊单，用于给患者发送问诊单
                    String patientWechatId = eventXML.getFromUserName();
                    SysPatient sysPatient = sysPatientService.selectByWechat(patientWechatId);
                    String xml =  buildTWXM2(patientWechatId, sysPatient.getPatientname() + ","+sysDoctor.getDoctorname()+"给您发来了一份问诊单",
                            server+"/mod-page/images/wechat/doctor_inquiry_guider.jpg",
                            server+"/mod-page/inquiry/inquiry-for-send.html?pid="+sysPatient.getPatientId()+"&did="+sysDoctor.getDoctorId()+"&_="+new Date().getTime(),
                            "前往填写-->",server+"/mod-page/images/wechat/howtofillform.png",server+"/mod-page/inquiry/inquiry-guider.html");
                    response.getWriter().write(xml);
                }
            }else if("subscribe".equals(eventType)){
                //以下为临时代码
                String doctorWechat = eventKey.replace("qrscene_","");

                if (doctorWechat==null||doctorWechat.length()<=0){
                    String xml = buildWBXML(eventXML.getFromUserName(),"自定义消息：欢迎来到杏林名家");
                    response.getWriter().write(xml);
                    return ;
                }
                char bizType = doctorWechat.charAt(0);
                //查询医生的信息
                SysDoctor docExample = new SysDoctor();
                docExample.setWechat(doctorWechat.substring(1));
                List<SysDoctor> sysDoctors = sysDoctorMapper.selectByExample(docExample);
                SysDoctor sysDoctor = null;
                if(sysDoctors!=null&&sysDoctors.size()>0){
                    sysDoctor  = sysDoctors.get(0);
                }
                if('#'==bizType){//# 患者扫描，添加患者
                    //判断是不是自己关注自己
                    if(sysDoctor.getWechat().equals(eventXML.getFromUserName())){
                        String xml  =buildWBXML(eventXML.getFromUserName(),"自己不能关注自己");
                        response.getWriter().write(xml);
                        return ;
                    }
                    SysPatient  sysPatient = sysPatientService.selectByWechat(eventXML.getFromUserName());
                    SysWechatAccount wechatAccount = fetchWechatInfo(eventXML.getFromUserName());
                    if(sysPatient==null) {//库中没有记录，插入
                        sysPatient = new SysPatient();
                        sysPatient.setPatientname(wechatAccount.getNickname());
                        sysPatient.setWechat(eventXML.getFromUserName());
                        sysPatient.setSex("0".equals(wechatAccount.getSex()) ? "男" : "女");
                        sysPatient.setPatientCreatedate(new Date());
                        sysPatient.setPatientPicPath(wechatAccount.getHeadimgurl());
                        sysPatientService.insert(sysPatient);
                    }
                    //查关系表是不是已经有关注
                    DPRelationship example = new DPRelationship();
                    example.setPatientId(sysPatient.getPatientId());
                    example.setDoctorId(sysDoctor.getDoctorId());
                    List  dprList = dpRelationshipMapper.selectByExample(example);
                    if(dprList==null||dprList.size()==0){
                        DPRelationship dpRelationship  = new DPRelationship();
                        dpRelationship.setDoctorId(sysDoctor.getDoctorId());
                        dpRelationship.setDpCreatetiondate(new Date());
                        dpRelationship.setPatientId(sysPatient.getPatientId());
                        dpRelationshipMapper.insert(dpRelationship);
                    }

                    //如果没有绑定微信，加一条数据
                    SysWechatAccount wechatExample = new SysWechatAccount();
                    wechatExample.setOpenid(wechatAccount.getOpenid());
                    List<SysWechatAccount> accounts = sysWechatAccountMapper.selectByExample(wechatExample);
                    if(accounts==null||accounts.size()<=0){
                        wechatAccount.setUuid(IDGenerator.uuid());
                        sysWechatAccountMapper.insert(wechatAccount);
                    }
                    String xml  =buildWBXML(eventXML.getFromUserName(),"您已成功关注"+sysDoctor.getDoctorname()+"医生，请尽快&lt;a href=&quot;"+server+"/mod-page/patient/patient_info_detail_extract.html?patientId="+sysPatient.getPatientId()+"&quot;&gt;完善您的个人信息&lt;/a&gt;，以方便医生诊断");
                    response.getWriter().write(xml);
                }
            }
        }
    }
    /**
     * 构建图文消息
     *
     * @return
     */
    private String buildTWXML(String toUser, String title, String img, String link, String desc) {
        return "<xml><ToUserName><![CDATA[" + toUser + "]]></ToUserName><FromUserName><![CDATA[" + PropertyUtil.getConfig("wechat.originId") + "]]></FromUserName>" +
                "<CreateTime>" + new Date().getTime() + "</CreateTime><MsgType><![CDATA[news]]></MsgType><ArticleCount>1</ArticleCount><Articles><item>" +
                "<Title><![CDATA[" + title + "]]></Title> <Description><![CDATA[" + desc + "]]></Description><PicUrl><![CDATA[" + img + "]]>" +
                "</PicUrl><Url><![CDATA[" + link + "]]></Url></item></Articles></xml>";
    }

    /**
     * 构建图文消息2
     *
     * @return
     */
    private String buildTWXM2(String toUser, String title, String img, String link, String desc,String img2,String link2) {
        return "<xml><ToUserName><![CDATA[" + toUser + "]]></ToUserName><FromUserName><![CDATA[" + PropertyUtil.getConfig("wechat.originId") + "]]></FromUserName>" +
                "<CreateTime>" + new Date().getTime() + "</CreateTime><MsgType><![CDATA[news]]></MsgType><ArticleCount>2</ArticleCount><Articles><item>" +
                "<Title><![CDATA[" + title + "]]></Title> <Description><![CDATA[" + desc + "]]></Description><PicUrl><![CDATA[" + img + "]]>" +
                "</PicUrl><Url><![CDATA[" + link + "]]></Url></item><item><Title><![CDATA[如何填写问诊单才更高效]]></Title><Description><![CDATA[如何填写问诊单才更高效]]></Description><PicUrl><![CDATA["+img2+"]]></PicUrl><Url><![CDATA["+link2+"]]></Url></item></Articles></xml>";
    }

    /**
     * 构建文本信息消息
     *
     * @return
     */
    private String buildWBXML(String toUser, String content) {
        return "<xml><ToUserName><![CDATA[" + toUser + "]]></ToUserName><FromUserName><![CDATA[" + PropertyUtil.getConfig("wechat.originId") + "]]></FromUserName>" +
                "<CreateTime>" + new Date().getTime() + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content>"+content+"</Content></xml>";
    }


    private TextXML parseTextObject(Element root) {
        // toUserName,  fromUserName,  createTime,  msgType,  content,  msgId
        return new TextXML(root.selectSingleNode("ToUserName").getText(),
                root.selectSingleNode("FromUserName").getText(),
                root.selectSingleNode("CreateTime").getText(),
                root.selectSingleNode("MsgType").getText(),
                root.selectSingleNode("Content").getText(),
                root.selectSingleNode("MsgId").getText());
    }

    private EventXML parseEventObject(Element root) {
        // toUserName,  fromUserName,  createTime,  msgType,  content,  msgId
        EventXML eventXML  = new EventXML(root.selectSingleNode("ToUserName").getText(),
                root.selectSingleNode("FromUserName").getText(),
                root.selectSingleNode("CreateTime").getText(),
                root.selectSingleNode("MsgType").getText(),
                root.selectSingleNode("Event").getText(),
                root.selectSingleNode("EventKey").getText());
        String ticket = root.selectSingleNode("Ticket")==null?null:root.selectSingleNode("Ticket").getText();
        if(ticket!=null)
            eventXML.setTicket(ticket);
        return eventXML;
    }

    // 根据open id 获取微信用户信息
   private  SysWechatAccount  fetchWechatInfo(String wechat){
        //获取微信用户信息
        String accessToken = WechatUtil.getAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + accessToken + "&openid=" + wechat + "&lang=zh_CN";
        String responseJson = HttpUtil.sendGetRequest(url, null);
        log.debug("responseJson:" + responseJson);
        responseJson=responseJson.replaceAll("[\\ud800\\udc00-\\udbff\\udfff\\ud800-\\udfff]","");
        return  JSONObject.parseObject(responseJson, SysWechatAccount.class);
    }



    public boolean sendNews(JSONNewsEntity articles){
        String token   = WechatUtil.getAccessToken();
        String url  = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+token;
        String json = JSONObject.toJSONString(articles);
        //String json = "{\"touser\":\""+toOpenId+"\",\"msgtype\":\"text\",\"text\":{\"content\":\""+msg+"\"}}";
        String response  =   HttpUtil.sendPostRequest(url,json,"json");
        log.debug("wcresponse:"+response);
        return  true;
    }


    public static void main(String ar[]){
        /** 发送 公众号消息--代带链接
       /* String token   = WechatUtil.getAccessToken();
        System.out.println("token:"+token);
        String url  = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+token;
        String json = "{\"touser\":\"ozT4P1f-laLUn7-wbhzTXufwACt0\",\"msgtype\":\"text\",\"text\":{\"content\":\"Hello World <a href='http://www.baidu.com'>自动回复</a>；\"}}";
        String msg  =   HttpUtil.sendPostRequest(url,json,"json");
        System.out.println("msg:"+msg);*/

        String token   = WechatUtil.getAccessToken();
        System.out.println("token:"+token);
        String url  = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token="+token;
        String url1="";
        String url2="";
        try {
             url1 = java.net.URLEncoder.encode(PropertyUtil.getConfig("app.server")+"/wechat/userauth","UTF-8");
             url2 = java.net.URLEncoder.encode(PropertyUtil.getConfig("app.server")+"/wcpay/wcuser","UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String menu1 = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+PropertyUtil.getConfig("wechat.appId")+"&redirect_uri="+url1+"&response_type=code&scope=snsapi_base&state=zxzy#wechat_redirect";
        String menu2 = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+PropertyUtil.getConfig("wechat.appId")+"&redirect_uri="+url1+"&response_type=code&scope=snsapi_base&state=wdbl#wechat_redirect";
        String menu3 = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+PropertyUtil.getConfig("wechat.appId")+"&redirect_uri="+url2+"&response_type=code&scope=snsapi_base&state=wdbl#wechat_redirect";


        String json = " {" +
                " \"button\": [{" +
                " \"type\": \"view\"," +
                " \"name\": \"咨询中医\"," +
                " \"url\": \""+menu1+"\"" +
                " }, {" +
                " \"type\": \"view\"," +
                " \"name\": \"商品列表\"," +
                " \"url\": \""+menu3+"\"" +
                " }, {" +
                " \"type\": \"view\"," +
                " \"name\": \"个人中心\"," +
                " \"sub_button\": [{" +
                " \"type\": \"view\"," +
                " \"name\": \"我的病例\"," +
                " \"url\": \""+menu2+"\"" +
                " }]" +
                "" +
                " }]" +
                " }";
        System.out.println("json:"+json);
        String msg  =   HttpUtil.sendPostRequest(url,json,"json");
        System.out.println("msg:"+msg);
    }
}
